package com.reflect;

import org.springframework.util.StopWatch;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ReflectionPerformanceTest {

    private static final String CLASS_NAME = "org.example.localmessage.LocalMsgAspect";
    private static final String METHOD_NAME = "get";
    private static final int ITERATIONS = 10_000_000;

    public static void main(String[] args) throws Exception {
        // 测试直接反射调用性能
        testDirectReflection();
        
        // 测试缓存反射对象性能
        testCachedReflection();
    }

    private static void testDirectReflection() throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        
        for (int i = 0; i < ITERATIONS; i++) {
            Class<?> aClass = Class.forName(CLASS_NAME);
            Method method = aClass.getMethod(METHOD_NAME);
        }
        
        stopWatch.stop();
        System.out.println("直接反射调用耗时: " + stopWatch.getTotalTimeMillis() + " ms");
    }

    private static void testCachedReflection() {
        Map<String, Object> reflectionCache = new HashMap<>();
        
        try {
            reflectionCache.put("class", Class.forName(CLASS_NAME));
            reflectionCache.put("method", Class.forName(CLASS_NAME).getMethod(METHOD_NAME));
        } catch (Exception e) {
            throw new RuntimeException("初始化反射缓存失败", e);
        }

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        
        for (int i = 0; i < ITERATIONS; i++) {
            Method method = (Method) reflectionCache.get("method");
        }
        
        stopWatch.stop();
        System.out.println("缓存反射调用耗时: " + stopWatch.getTotalTimeMillis() + " ms");
    }
}